Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Merge Strings Alternately

Problem Statement

Given two strings, word1 and word2, return the merged string after merging each character of both strings in alternate order, starting with the word1. If one string is longer than the other, append the remaining characters of the longer string to the end of the merged string.

Examples

  • Example 1:

    • Input: word1: "dog", word2: "cat"
    • Expected Output: "dcoagt"
    • Justification: The characters from both strings are alternated, starting with the first character of the first string. Since both strings are of equal length, no extra characters remain at the end.
  • Example 2:

    • Input: word1: "hello", word2: "hi"
    • Expected Output: "hheillo"
    • Justification: After alternating characters from both strings, the remaining characters from the longer string ("hello") are appended to the end.
  • Example 3:

    • Input: word1: "abc", word2: "xyz123"
    • Expected Output: "axbycz123"
    • Justification: Characters are alternated, and since the second string is longer, the remaining characters ("123") are appended to the end.

Solution

To solve this problem, we'll iterate over both strings simultaneously, appending one character from each string to the result until we reach the end of one of the strings. This approach ensures that characters are merged in an alternating fashion, preserving the order from both input strings. After completing the alternating merge, if one string is longer, we append the remaining characters of the longer string to the merged result. This method is effective because it directly addresses the problem's requirements with a straightforward iteration, making it easy to understand and implement. By iterating over the strings simultaneously, we minimize the time complexity, ensuring that each character is visited only once, which makes the algorithm efficient for strings of varying lengths.

Step-by-Step Algorithm

  • Initialize an empty string result to store the merged output.
  • Determine the length of the shorter string to ensure the alternating merge doesn't exceed the shorter string's length.
  • Use a loop to iterate through both strings up to the length of the shorter string. During each iteration:
    • Append the current character from the first string to result.
    • Append the current character from the second string to result.
  • After completing the alternating merge, check if any string has remaining characters. Append the remaining characters from the longer string to result.
  • Return the result string.

Algorithm Walkthrough

Consider the input: word1: "abc", word2: "xyz123"

  1. Initialize Variables:

    • result is an empty string where the merged output will be stored.
    • Determine the length of the shorter string. In this case, word1 has a length of 3, and word2 has a length of 6. So, the length of the shorter string is 3.
  2. Start Looping Through Both Strings:

    • For i = 0 (first iteration):
      • Append the first character of word1 ("a") to result. Now, result = "a".
      • Append the first character of word2 ("x") to result. Now, result = "ax".
    • For i = 1 (second iteration):
      • Append the second character of word1 ("b") to result. Now, result = "axb".
      • Append the second character of word2 ("y") to result. Now, result = "axby".
    • For i = 2 (third iteration):
      • Append the third character of word1 ("c") to result. Now, result = "axbyc".
      • Append the third character of word2 ("z") to result. Now, result = "axbycz".
  3. Check for Remaining Characters:

    • At this point, word1 is fully iterated through, but word2 still has characters left ("123").
    • Since word1 is shorter and fully merged, we append the remaining characters of word2 to result. Now, result = "axbycz123".
  4. Return the Result:

    • The final merged string is "axbycz123", which is stored in result.
    • Return result.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

  • Time Complexity: , where N is the length of the first string and M is the length of the second string. This is because the algorithm iterates through both strings once.

  • Space Complexity:| , due to the storage requirements for the resulting string which combines characters from both input strings.

Merge Strings Alternately (easy)
Reverse a LinkedList (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis